package com.loan.controller;
import java.io.UnsupportedEncodingException;
import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang.StringUtils;
import org.apache.shiro.SecurityUtils;
import org.apache.shiro.authc.UsernamePasswordToken;
import org.apache.shiro.authz.annotation.Logical;
import org.apache.shiro.authz.annotation.RequiresRoles;
import org.apache.shiro.subject.Subject;

import com.alibaba.fastjson.JSONObject;
import com.jfinal.aop.Before;
import com.jfinal.aop.Clear;
import com.jfinal.core.Controller;
import com.jfinal.ext.interceptor.SessionInViewInterceptor;
import com.jfinal.plugin.activerecord.Db;
import com.jfinal.plugin.activerecord.Page;
import com.loan.common.CONST;
import com.loan.enums.S;
import com.loan.model.Bank;
import com.loan.model.Company;
import com.loan.model.Data;
import com.loan.model.Loan;
import com.loan.model.Repay;
import com.loan.model.Role;
import com.loan.model.Staff;
import com.loan.model.User;
import com.loan.service.LoanService;
import com.loan.service.LoggerService;
import com.loan.service.RoleService;
import com.loan.service.StaffService;
import com.loan.service.TokenService;
import com.loan.service.UserService;
import com.loan.util.AES;
import com.loan.util.CheckIdCard;
import com.loan.util.CheckUtils;
import com.loan.util.DateUtil;
import com.loan.util.FileUtil;
import com.loan.util.Gateway;
import com.loan.util.Http;
import com.loan.util.Json;
import com.loan.util.MD5Util;
import com.loan.util.Str;

/**
 *  用户控制器
 * @since 2018-06-01
 * @author 无处不在的二叔
 */ 
public class UserController extends Controller {
	private static RoleService role = new RoleService();
	private static UserService user = new UserService();
	private static StaffService staff = new StaffService();
	private static LoanService loan = new LoanService();
	private static LoggerService log = new LoggerService(); 
	private static TokenService token = new TokenService();
	
	@Clear
	public void test2() {
		List<Loan> list = Loan.dao.find("select * from loan");
		for(Loan ln : list) {
			Repay rp = Repay.dao.findFirst("select * from repay where loan_id=? order by repay_time desc",ln.getId());
			if(rp!=null) {
				ln.setStartTime(rp.getCreateTime()).setEndTime(rp.getRepayTime()).setRemittanceTime(rp.getCreateTime()).update();
			}
		}
	}
	
	/**
	 * 页面控制器
	 */
	@Clear 
	@Before({SessionInViewInterceptor.class})
	public void index() throws Exception {
		String page = getPara(0);
		if(!Str.nb(page)) {
			page = "index";
		}
		render(page+".html");
	} 
	
	/**
	 * 用户登录
	 */
	@Clear
	public void login() throws UnsupportedEncodingException { 
		getResponse().setHeader("Access-Control-Allow-Origin","*"); 
		int aes = getParaToInt("aes",1);
		String workcode = getPara("workcode");
		String mobile = getPara("mobile","");
		int cid = getParaToInt("cid",2);
		String password = getPara("password","");
		String type = getPara("type");
		Date now = new Date();
		
		// AES解密
		if(aes==1) {
			mobile = AES.decode(mobile);
			password = AES.decode(password);
		}
		 
		// 后台工号-手机号转换
		Role r = new Role();
		String r2 = "";
		if(Str.eq("backend", type) && Str.nb(workcode)) {
			Staff s = staff.findByWorkcode(workcode.toUpperCase());
			if(s!=null) {
				mobile = s.getMobile();
				cid = s.getCid();
			}else{
				renderJson(Json.error("工号不正确！"));
				return;
			}	
		}
		User u = user.findByMobile(cid,mobile);
		if(u!=null && Str.eq("正常", u.getStatus())) {
			if(u.getErrorCount()<4 || now.compareTo(u.getErrorLockTime())>0) {
				if(Str.nb(mobile) && Str.nb(password)){ 
					try {
						// 进行用用户名和密码验证,如果验证不过会throw exception
						// User u = user.checkLogin(mobile,MD5Util.encrypt(password));
						UsernamePasswordToken upt = new UsernamePasswordToken(mobile, password, false, type+","+cid);
				        Subject subject = SecurityUtils.getSubject();
				        subject.login(upt);
						u.setLoginTime(new Date()).setLoginType(type).setErrorCount(0).update();

						// 刷新用户token
						String tk = token.refresh(u, type);
						setSessionAttr("userId", u.getId());
						 
						// 后台登录需要判断是否是员工
						if(Str.eq("backend", type)) {
							Staff s = staff.findByUserId(u.getId());
							if(s!=null) {
								setSessionAttr("token2", tk);
								//role = s.getRole();
								r2 = s.getRole();
								r = role.getInfo(u.getCid(),r2);
								// Sms.send("13736169222", u.getMobile()+"("+u.getRealName()+")于"+DateUtil.getNowDateAndTime()+"登陆后台！");
							}else {
								renderJson(Json.error("您不是员工身份，不可登录！"));
								return;
							}
						}else {	
							setSessionAttr("token", token);
						}

						// 敏感信息加密
						if(aes==1) {
							u.setCertNum(AES.encode(u.getCertNum()));
						}
						
						// 日志记录
						log.build("登录", "用户登录", u.getId(), Str.eq("backend", type) ? "backend" : "user");
						Loan ln = loan.findProcess(u.getId());
						u.put("loanId",ln!=null?ln.getId():0);
						u.put("loanStatus",ln!=null?ln.getStatus():"");
						renderJson(Json.ok("登录成功！", Data.put("token",tk,"info",u,"company",u.getCname(),"role",r2,"menu",r)));
						
					} catch (Exception e) {
						u.setErrorCount(u.getErrorCount()+1);
						if(u.getErrorCount()>=4) {
							u.setErrorLockTime(new Date(now.getTime()+43200000));
						}
						u.update();
						renderJson(Json.error("手机号或密码不正确！\n(剩余可尝试"+(5-u.getErrorCount())+"次)"));
					}
				}else{ 
					renderJson(Json.error("手机号或密码不能为空！"));
				}
			}else{   	
				renderJson(Json.error("错误次数已达上限，请在"+DateUtil.format(u.getErrorLockTime(), DateUtil.DATETIME_LOCAL_FORMAT)+"后重试！"));
			}
		}else{ 
			renderJson(Json.error("用户未注册或状态不正确！"));
		}
	}
	
	/** 
	 * 用户注册
	 * @throws Exception 
	 */
	@Clear
	public void reg() throws Exception {
		getResponse().setHeader("Access-Control-Allow-Origin","*"); 
		int aes = getParaToInt("aes",1);
		String mobile = aes==1 ? AES.decode(getPara("mobile")) : getPara("mobile");
		String password = aes==1 ? AES.decode(getPara("password")) : getPara("password");
		String sms = getPara("sms");
		String type = getPara("type","iOS"); 
		int cid = getParaToInt("cid",2);

		if(CheckUtils.checkPassword(password)){ 
			if(CheckUtils.checkMoible(mobile) && Str.nb(password)){
				
				if(sms.length()==4 && StringUtils.equals(sms, CONST.getAttr("reg"+mobile))){
					if(!user.isExistMobile(cid,mobile)){ 
						
						// 开始注册用户 
						User u = new User();
						u.setMobile(mobile); 
						u.setPassword(MD5Util.encrypt(password)); 
						u.setCreateTime(new Date()); 
						u.setStatus("正常"); 
						u.setErrorCount(0);
						u.setLoginTime(new Date());
						u.setLoginType(type);
						u.setRealName("");
						u.setCertNum("");
						u.setAgentId(0);
						u.setCid(0);
						u.setCname("");
						u.setAgentId(0);
						u.setCertVerifyStatus("待认证");
						u.setInfoVerifyStatus("待认证");
						u.setCardVerifyStatus("待认证");
						u.setServiceVerifyStatus("待认证");
						u.setChecks(S.WAIT);  
						Company c = Company.dao.findById(getParaToInt("cid"));
						u.setCid(c.getId());
						u.setCname(c.getName());
						u.setSex("男");
						
						if(u.save()){
							
							// 刷新用户token
							String tk = token.refresh(u, type);
							setSessionAttr("token", tk);
							CONST.removeAttr("reg"+mobile); 
							
							// 日志记录
							log.build("注册", "用户注册", u.getId(), "user");
							
							renderJson(Json.ok("注册成功！", Data.put("token",tk,"info",u)));
						}else{
							renderJson(Json.error("数据保存失败！"));
						}
					}else{
						renderJson(Json.error("手机号已存在，请修改！"));
					}
				}else{
					renderJson(Json.error("手机验证码不正确！"));
				}
			}else{	
				renderJson(Json.error("手机号或密码格式不正确！"));
			}
		}else{	
			renderJson(Json.error("密码长度不可小于6位！"));
		}
	}
	
	/**
	 * 修改登录密码
	 */
	public void modifyPassword() {
		int aes = getParaToInt("aes",1);
		String mobile = getPara("mobile","");
		String passwordOld = getPara("passwordOld","");
		String passwordNew = getPara("passwordNew","");
		String passwordNew2 = getPara("passwordNew2","");
		String sms = getPara("sms");
		User t = getAttr("user");
		
		// AES解密
		if(aes==1) {
			mobile = AES.decode(mobile);
			passwordOld = AES.decode(passwordOld);
			passwordNew = AES.decode(passwordNew);
			passwordNew2 = AES.decode(passwordNew2);
		}

		if(Str.nb(sms)){ 
			if(Str.nb(passwordOld) && CheckUtils.checkPassword(passwordOld)){
				User u = user.checkLogin(t.getCid(),mobile,MD5Util.encrypt(passwordOld));
				if(u!=null && Str.eq(sms, CONST.getAttr("modifyPassword"+mobile))){
					if(Str.eq(passwordNew, passwordNew2)) {
						if(Str.ne(u.getPassword(), MD5Util.encrypt(passwordNew))){
							u.setPassword(MD5Util.encrypt(passwordNew)).setErrorCount(0).update();
							CONST.removeAttr("modifyPassword"+mobile);
							log.build("设置", "用户修改登录密码成功", u.getId(), "user");
							renderJson(Json.ok("修改成功！"));
						}else{
							renderJson(Json.error("新密码不可与原密码一致！"));
						}
					}else{
						renderJson(Json.error("两次新密码输入不一致！"));
					}
				}else{
					renderJson(Json.error("旧密码或短信验证码不正确！"));
				}
			}else{	
				renderJson(Json.error("密码格式不正确！"));
			}
		}else{	
			renderJson(Json.error("验证码不可为空！"));
		}
	}
	
	/**
	 * 银行卡信息认证
	 */
	public void bankCardVerify() {
		User u = getAttr("user");
		if(Str.ne(S.PASS, u.getCardVerifyStatus())){
			int aes = getParaToInt("aes",1);
			String bankId = getPara("bankId");
			String bankCard = getPara("bankCard");
			String bankCardProvince = getPara("bankCardProvince");
			String bankCardCity = getPara("bankCardCity");
			Bank b = Bank.dao.findById(bankId);
			// AES解密
			if(aes==1) {
				bankCard = AES.decode(bankCard);
			}
			u.setCardVerifyStatus(S.VERIFY)
				.setBankName(b.getName())
				.setBankCard(bankCard)
				.setBankCardProvince(bankCardProvince)
				.setBankCardCity(bankCardCity)
				.setBindCardTime(new Date())
				.update();
			u.refreshStatus();
			renderJson(Json.ok("信息提交成功，请等待审核！"));
		}else {
			renderJson(Json.error("已完成认证！"));
		}
	}
	 
	/**
	 * 身份证信息认证
	 * @throws Exception 
	 */
	public void realnameVerify() throws Exception {
		User u = getAttr("user");
		if(Str.ne(S.PASS, u.getCertVerifyStatus())) {
			String certNum = getPara("certNum");
			CheckIdCard card = new CheckIdCard(certNum);
			if(card.validate()){ 
				u.setRealName(getPara("realName"));  
				u.setCertNum(certNum);	//身份证号码
				u.setBirthday(card.getBirthday());	// 第7~14位数字表示：出生年、月、日
				u.setSex(card.isMale()?"男":"女"); // 第17位数字表示性别：奇数表示男性，偶数表示女性； 
				u.setAge(card.getAge());
				u.setCertFront(FileUtil.download(getPara("certFront")));
				u.setCertBack(FileUtil.download(getPara("certBack")));
				if(Str.nb(getPara("manPic"))) {
					u.setManPic(FileUtil.download(getPara("manPic")));
				}
				u.setCertVerifyStatus(S.VERIFY);
				u.update();
				u.refreshStatus();
				renderJson(Json.ok("信息提交成功，请等待审核！"));
			}else{
				renderJson(Json.error("身份证信息不正确！"));
				return;
			}
		}else {
			renderJson(Json.error("已完成认证！"));
		}
	}
	
	/**
	 * 用户画像
	 * @throws Exception
	 */
	public void portrait() throws Exception {
		JSONObject json = new JSONObject();
		json.put("id_no", getPara("certNum"));
		JSONObject res = Gateway.post("Y1001005", json);
		if(Str.eq("1", res.getString("status"))) {
			renderJson(Json.ok("信息获取成功！",res));
		}else {
			renderJson(Json.error("信息获取失败！",res));
		}
	}

	/**
	 * 用户通讯回调
	 * @throws Exception
	 */
	@Clear
	public void contactNotify() throws Exception {
		/**String notifyEvent = getPara("notify_event");
		if(Str.eq("SUCCESS", notifyEvent)){
			JSONObject json = JSONObject.parseObject(getPara("notify_data"));
			String taskId = json.getString("task_id");
			json = JSONObject.parseObject(json.getString("data"));
			String certNum = json.getString("identity_code");
			User u = user.findByCertNum(certNum);
			u.setServiceVerifyStatus(S.VERIFY).setTaskId(taskId).update();
			u.refreshStatus();
		}*/
		renderJson("{\"message\": \"回调处理成功\",\"code\": 0}");
	}
	
	/**
	 * 用户通讯记录
	 * @throws Exception
	 */
	public void contactInfo() throws Exception {
		User u =User.dao.findById(getParaToInt("id"));
		if(Str.nb(u.getTaskId())) {
			String url = "https://report.shujumohe.com/report/"+u.getTaskId()+"/"+getToken();
			renderJson(Json.ok("信息获取成功！",url));
		}else{
			renderJson(Json.error("未通过第三方审核！"));
		}
	}

	/**
	 * 获取魔盒token
	 * @throws Exception
	 */
	private String getToken() {
		String url = "https://report.shujumohe.com/report/getToken";
        Map<String, String> params = new HashMap<String, String>();  
        params.put("partner_code", "bjhs_mohe");  
        params.put("partner_key", "8e86006a55f44f58a3e7dab51691f242");  
		JSONObject res = JSONObject.parseObject(Http.get(url,params));
		return res.getString("data");
	}
	
	/**
	 * 个人信息认证
	 */
	public void infoVerify() {
		User u = getAttr("user");
		if(Str.ne(S.PASS, u.getInfoVerifyStatus())) {
			Map<String,String> params = Data.flat(getParaMap());
			for(String key : params.keySet()) {
				if(Str.isBlank(params.get(key))) {
					renderJson(Json.error("数据不可为空！"));
					return ;
				}
			}
			u.setRealName(getPara("realName"));
			u.setCertValidDay(getPara("certValidDay"));
			u.setAlipay(getPara("alipay"));
			u.setWechat(getPara("wechat"));
			
			u.setAddress(getPara("address"));
			u.setAddressDetail(getPara("addressDetail"));
			u.setAddressLiveLong(getPara("addressLiveLong"));
			u.setCompany(getPara("company"));
			u.setCompanyPhone(getPara("companyPhone")); 
			u.setCompanyAddress(getPara("companyAddress"));
			u.setSector(getPara("sector"));
			u.setStation(getPara("station"));
			u.setIncome(getPara("income"));
			u.setEducation(getPara("education")); 
			u.setSesame(getPara("sesame"));  
			
			u.setContacts(Str.filterEmoji(getPara("contacts")));
			u.setContactsRelationship(getPara("contactsRelationship"));
			u.setContactsPhone(getPara("contactsPhone"));
			u.setContacts2(Str.filterEmoji(getPara("contacts2")));
			u.setContactsRelationship2(getPara("contactsRelationship2",getPara("contacts_relationship2")));
			u.setContactsPhone2(getPara("contactsPhone2",getPara("contacts_phone2")));
			u.setContacts3(Str.filterEmoji(getPara("contacts3")));
			u.setContactsRelationship3(getPara("contactsRelationship3",getPara("contacts_relationship3")));
			u.setContactsPhone3(getPara("contactsPhone3",getPara("contacts_phone3")));

			/**
			u.setContactsRelationship2(getPara("contacts_relationship2"));
			u.setContactsPhone2(getPara("contacts_phone2"));
			u.setContacts3(getPara("contacts3"));
			u.setContactsRelationship3(getPara("contacts_relationship3"));
			u.setContactsPhone3(getPara("contacts_phone3"));*/
			
			u.setInfoVerifyStatus(S.VERIFY).update();
			renderJson(Json.ok("信息提交成功，请等待审核！"));
		}else {
			renderJson(Json.error("已完成认证！"));
		}
	}

	/**
	 * 运营商信息认证
	 */
	public void serviceVerify() {
		User u = getAttr("user");
		if(Str.ne(S.PASS, u.getServiceVerifyStatus())) {
			if(Str.nb(u.getRealName()) && Str.nb(u.getCertNum())) {
				int aes = getParaToInt("aes",1);
				String mobile = getPara("mobile","");
				String serviceProvider = getPara("serviceProvider","");
				String servicePassword = getPara("servicePassword","");
				
				// AES解密
				if(aes==1) {
					mobile = AES.decode(mobile);
					servicePassword = AES.decode(servicePassword);
				}
				
				if(Str.nb(serviceProvider)) {
					u.setServiceProvider(serviceProvider).setServicePassword(servicePassword).update();
					renderJson(Json.ok("信息提交成功，请等待审核！","https://open.shujumohe.com/box/yys?cb=http%3A%2F%2F47.96.105.208%2Fuser%2FcontactNotifyPage%3Fid%3D"+u.getId()+"&box_token=4F77DEE721BC4C2F89D3EFB202012F10&real_name="+u.getRealName()+"&identity_code="+u.getCertNum()+"&user_mobile="+u.getMobile()));
				}else {
					renderJson(Json.error("信息不可为空！"));
				}
			}else {
				renderJson(Json.error("请先完成认证！"));
			}
		}else {
			renderJson(Json.error("已完成认证！"));
		}
	}
	
	/**
	 * 用户通讯回调
	 * @throws Exception
	 */
	@Clear
	public void contactNotifyPage() throws Exception {
		User u = User.dao.findById(getParaToInt("id"));
		String taskId = getPara("task_id");
		if(u!=null){
			u.setServiceVerifyStatus(S.VERIFY).setTaskId(taskId).update();
		}
		render("/contactNotifyPage.html");
	}
	
	/**
	 * 修改手机号
	 */
	public void modifyMobile() throws Exception {
		User u = getAttr("user");
		String sms1 = getPara("sms1",getPara("sms"));
		String sms2 = getPara("sms2","");
		String mobileOld = getParaToInt("aes",1)==1?AES.decode(getPara("mobileOld","")):getPara("mobileOld","");
		String mobileNew = getParaToInt("aes",1)==1?AES.decode(getPara("mobileNew","")):getPara("mobileNew","");

		if(user.isExistMobile(u.getCid(),mobileOld)){ 
			if(CheckUtils.checkMoible(mobileOld)  && Str.eq(sms1,CONST.getAttr("modifyMobileOld"+mobileOld))){
				if(!user.isExistMobile(u.getCid(),mobileNew)){ 
					if(CheckUtils.checkMoible(mobileNew)  && StringUtils.equals(sms2,CONST.getAttr("modifyMobileNew"+mobileNew))){
						user.refreshMobile(u.getCid(),u.getMobile(),mobileNew);
						u.setMobile(mobileNew).update(); 
						log.build("修改手机号", "用户修改手机号成功", u.getId(), "user");
						renderJson(Json.ok("新手机号修改成功！"));
					}else{
						renderJson(Json.error("新手机短信验证码错误！"));
					}
				} else {
					renderJson(Json.error("该手机号已注册！"));
				}
			} else {
				renderJson(Json.error("短信验证码错误！"));
			}
		} else {
			renderJson(Json.error("该手机号不存在！"));
		}
	}
	
	/**
	 * 重置登录密码
	 */
	@Clear
	public void resetPassword() {
		int aes = getParaToInt("aes",1);
		String mobile = getPara("mobile","");
		String password = getPara("password","");
		String sms = getPara("sms");
		int cid = getParaToInt("cid",2);
		
		// AES解密
		if(aes==1) {
			mobile = AES.decode(mobile);
			password = AES.decode(password);
		}

		if(Str.nb(sms)){
			if(Str.nb(password) && CheckUtils.checkPassword(password)){
				User u = user.findByMobile(cid,mobile);
				if(u!=null && Str.eq(sms, CONST.getAttr("resetPassword"+mobile))){
					if(Str.ne(u.getStr("password"), MD5Util.encrypt(password))){
						u.set("password", MD5Util.encrypt(password)).setErrorCount(0).update();
						CONST.removeAttr("ressetPassword"+mobile);
						log.build("设置", "用户设置登录密码成功", u.getId(), "user");
						renderJson(Json.ok("修改成功！"));
					}else{
						renderJson(Json.error("新密码不可与原密码一致！"));
					}
				}else{
					renderJson(Json.error("手机验证码不正确！"));
				}
			}else{
				renderJson(Json.error("密码格式不正确！"));
			}
		}else{	
			renderJson(Json.error("验证码不可为空！"));
		}
	}
	
	/**
	 * 用户列表
	 */ 
	public void list() { 
		User u = getAttr("user");
		int page = getParaToInt("page",1);
		int size = getParaToInt("size",10);	
		Map<String,String> params = Data.flat(getParaMap());
		if(u.getCid()>1) {
			params.put("cid", String.valueOf(u.getCid()));
		}
		Page<User> p = user.list(page,size,params);
		p.getList().forEach(n->{
			if(n.getAgentId()>0) {
				n.put("agent", User.dao.findById(n.getAgentId()));
			} 
			n.put("count", loan.count(n.getId()));
			n.put("loan", loan.findOne(n.getId()));
		});
		renderJson(Json.ok("数据获取成功！", Data.put("page",p)));
	}
	
	/**
	 * 根据ID获取用户信息
	 * @throws Exception 
	 */
	public void info() {	
		int id = getParaToInt("id",((User)getAttr("user")).getId());
		User u = User.dao.findById(id);
		if(1!=getParaToInt("admin",0)) {
			u.setPhoneBook("");
		}else {
			u.setReason("");
		}
		if(u.getAgentId()>0) {
			u.put("agent", User.dao.findById(u.getAgentId()));
		}				
		Loan ln = loan.findProcess(u.getId());
		u.put("loanId",ln!=null?ln.getId():0);
		u.put("loanStatus",ln!=null?ln.getStatus():"");
		renderJson(Json.ok("信息获取成功！", u));
	}
	
	/**
	 * 更新通讯录信息
	 */ 
	public void phoneBook() { 
		User u = getAttr("user");
		u.setIsPhoneBook(1).setPhoneBook(Str.filterEmoji(getPara("phoneBook"))).update();
		renderJson(Json.ok("操作成功！"));
	}
	
	/**
	 * 更新iCloud信息
	 */ 
	public void iCloud() { 
		User u = User.dao.findById(getParaToInt("id"));
		String iCloud = getPara("iCloud");
		if(u!=null && Str.nb(iCloud)) {
			u.setIcloud(iCloud).update();
			renderJson(Json.ok("操作成功！"));
		}else {
			renderJson(Json.error("信息不正确！"));
		}
	}

	/**
	 * 用户状态变更
	 */
	public void pass() {	
		User op = getAttr("user");
		User u = User.dao.findById(getParaToInt("id",0));
		String status = getPara("status");
		if(Str.eq(S.PASS, status)) {
			if(Str.eq(S.VERIFY, u.getCertVerifyStatus())) {
				u.setCertVerifyStatus(S.PASS);
			}
			if(Str.eq(S.VERIFY, u.getCardVerifyStatus())) {
				u.setCardVerifyStatus(S.PASS);
			}
			if(Str.eq(S.VERIFY, u.getServiceVerifyStatus())) {
				u.setServiceVerifyStatus(S.PASS);
			}
			if(Str.eq(S.VERIFY, u.getInfoVerifyStatus())) {
				u.setInfoVerifyStatus(S.PASS);
			}
			u.update();
			u.refreshStatus();
		}else if(Str.eq(S.REJECT, status)) {
			if(Str.eq(S.VERIFY, u.getCertVerifyStatus())) {
				u.setCertVerifyStatus(S.REJECT);
			}
			if(Str.eq(S.VERIFY, u.getCardVerifyStatus())) {
				u.setCardVerifyStatus(S.REJECT);
			}
			if(Str.eq(S.VERIFY, u.getServiceVerifyStatus())) {
				u.setServiceVerifyStatus(S.REJECT);
			}
			if(Str.eq(S.VERIFY, u.getInfoVerifyStatus())) {
				u.setInfoVerifyStatus(S.REJECT);
			}
			u.setChecks(S.FCHECK_REJECT).setReason(getPara("reason")).update();
			loan.findProcess(u.getId()).setCheckTime(new Date()).setStatus(S.REJECT).setReason(getPara("reason")).update();
		}
		log.build("修改状态", u.getCid()+"一键修改"+u.getRealName()+"状态："+status, op.getId(), "admin");
		renderJson(Json.ok("用户状态变更成功！", u));
	}
	
	/**
	 * 用户状态变更
	 */ 
	public void status() {	
		User op = getAttr("user");
		User u = User.dao.findById(getParaToInt("id",0));
		String reason = getPara("reason");
		if(Str.nb(reason)) {
			u.setReason(u.getReason()+reason+";");
		}
		u.set(getPara("field","status"), getPara("status")).update();
		if(Str.eq(S.REJECT, getPara("status"))) {
			u.setChecks(S.FCHECK_REJECT).update();
			Loan ln = loan.findProcess(u.getId());
			ln.setStatus(S.REJECT).setReason(reason).update();
		}else {
			u.refreshStatus();
		}
		log.build("修改状态", u.getCid()+"修改"+u.getRealName()+"状态"+getPara("field")+getPara("status"), op.getId(), "admin");
		renderJson(Json.ok("用户状态变更成功！", u));
	}
	
	/**
	 * 用户信息修改
	 */
	public void edit() {	
		User op = getAttr("user");
		User u = User.dao.findById(getParaToInt("id"));
		if(u!=null) {
			u.setRealName(getPara("real_name"));
			u.setSex(getPara("sex"));
			u.setAge(getParaToInt("age"));
			u.setCertNum(getPara("cert_num"));
			u.setContacts(getPara("contacts"));
			u.setContactsRelationship(getPara("contacts_relationship"));
			u.setContactsPhone(getPara("contacts_phone"));
			u.setContacts2(getPara("contacts2"));
			u.setContactsRelationship2(getPara("contacts_relationship2"));
			u.setContactsPhone2(getPara("contacts_phone2"));
			u.setContacts3(getPara("contacts3"));
			u.setContactsRelationship3(getPara("contacts_relationship3"));
			u.setContactsPhone3(getPara("contacts_phone3"));
			
			u.setCertValidDay(getPara("cert_valid_day"));
			u.setAlipay(getPara("alipay"));
			u.setWechat(getPara("wechat"));
			
			u.setAddress(getPara("address"));
			u.setAddressDetail(getPara("address_detail"));
			u.setAddressLiveLong(getPara("address_live_long"));
			u.setCompany(getPara("company"));
			u.setCompanyPhone(getPara("company_phone"));
			u.setCompanyAddress(getPara("company_address"));
			u.setSector(getPara("sector"));
			u.setStation(getPara("station"));
			u.setIncome(getPara("income"));
			u.setEducation(getPara("education")); 
			u.setSesame(getPara("sesame"));  
 
			u.setBankName(getPara("bank_name"));
			u.setBankCard(getPara("bank_card"));
			u.setBankCardProvince(getPara("bank_card_province"));
			u.setBankCardCity(getPara("bank_card_city"));
			
			u.update();
			
			log.build("修改", "修改用户信息", op.getId(), "admin");
			
			renderJson(Json.ok("用户信息修改成功！"));
		}else {
			renderJson(Json.error("用户信息不存在！"));
		}
	}
	

	/**
	 * 用户分配公司
	 */
	public void allot() {
		Company c = Company.dao.findById(getPara("cid"));
		if(c!=null) {
			String users = getPara("users");
			if(Str.nb(users)){
			    String[] args = Str.split(users,",");
			    for(String uid : args) {
			    	User.dao.findById(uid).setCid(c.getId()).setCname(c.getName()).update();
			    }
				renderJson(Json.ok("分配成功！"));
			}else{
				renderJson(Json.error("客户不可为空！"));
			}
		}else{
			renderJson(Json.error("企业信息不存在！"));
		}
	}
	
	/**
	 * 删除用户
	 */
	@RequiresRoles(logical=Logical.OR,value={"admin"})  
	public void del() {
		User op = getAttr("user");
		int uid = getParaToInt("id");
		User u = User.dao.findById(getPara("id"));
		if(u!=null) { 
			Db.update("delete from repay where user_id=?",uid);
			Db.update("delete from loan where user_id=?",uid);
			Db.update("delete from staff where user_id=?",uid);
			log.build("删除", "删除用户"+u.getMobile(), op.getId(), "admin");
			u.delete();
			renderJson(Json.ok("删除成功！"));
		}else{
			renderJson(Json.error("用户信息不存在！"));
		}
	}
}
 